/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.sdkj.dspservice.modules.sys.dao;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.sdkj.dspservice.common.base.dao.CrudDao;
import com.sdkj.dspservice.modules.sys.entity.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 菜单DAO接口
 * @author tm
 * @version 2020-11-23
 */
public interface UserDao extends CrudDao<User> {

    /**
     * 根据角色ID获取用户列表
     * @param roleId
     * @return
     */
    @Select({"select * from sys_user u left join sys_user_role ur on ur.user_id = u.id where u.delete_flag = '0' and ur.role_id = #{roleId}"})
    List<User> findListByRoleId(String roleId);

    /**
     * 查询账号使用个数
     * @param loginName
     * @return
     */
    @Select({"select count(*) from sys_user where login_name = #{loginName}"})
    Integer getCountByLoginName(@Param("loginName") String loginName);

    /**
     * 根据账号获取用户
     * @param loginName
     * @return
     */
    @Select({"select *, t.en_names as \"roleEnNames\", t.names as \"roleNames\" from sys_user a\n" +
            "    left join (\n" +
            "        select ur.user_id, string_agg(r.en_name, ',') as en_names, string_agg(r.name, ',') as names from sys_user_role ur left join sys_role r on r.id = ur.role_id group by ur.user_id\n" +
            "        ) t on t.user_id = a.id\n" +
            "where a.login_name = #{loginName}"})
    User getByLoginName(String loginName);

    /**
     * 根据账号获取用户
     * @param cdpUserId
     * @return
     */
    @Select({"select * from sys_user where cdp_user_id = #{cdpUserId}"})
    User getByCdpUserId(String cdpUserId);

    /**
     * 关联查询
     * @param wrapper
     * @return
     */
    @Select("select * " +
            "from sys_user a " +
            "left join (" +
            "   select a.user_id,string_agg(a.role_id,',') as haveRoleIds, string_agg(r.name,',') as roleNames, string_agg(r.en_name,',') as roleEnNames " +
            "   from sys_user_role a" +
            "   left join sys_role r on r.id = a.role_id" +
            "   where a.delete_flag = '0' and r.delete_flag = '0' group by user_id" +
            ")t on t.user_id = a.id" +
            "${ew.customSqlSegment}"
    )
    IPage<User> pageLink(IPage<User> page, @Param(Constants.WRAPPER) Wrapper<User> wrapper);
}
